package interview;

public class interview_02_07 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null) return null;
        int lena=1;
        ListNode p=headA;
        while(p.next!=null){
            lena++;
            p=p.next;
        }
        int lenb=1;
        p=headB;
        while(p.next!=null){
            lenb++;
            p=p.next;
        }

        if(lena<lenb){
            ListNode q=headB;
            p=headA;
            for(int i=0;i<lenb-lena;++i){
                q=q.next;
            }
            while(p!=null&&p!=q){
                p=p.next;
                q=q.next;
            }
            return p;
        }
        else{
            ListNode q=headB;
            p=headA;
            for(int i=0;i<lena-lenb;++i){
                p=p.next;
            }
            while(p!=null&&p!=q){
                p=p.next;
                q=q.next;
            }
            return p;
        }
    }
}
 class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }